package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.ICustomerService;

/** 
 * 客户操作的实现
 *
 * @author Shao-Fei Fan 
 * @version 1.0,2017年9月8日 下午8:50:56 
 */
@Service
@Transactional
public class CustomerServiceImpl implements ICustomerService {
	
	@Autowired
	private CustomerRepository customerRepository;
	
	
	/**
	 * @see cn.itcast.crm.service.ICustomerService#findNoAssociationCustomers()
	 */
	@Override
	public List<Customer> findNoAssociationCustomers() {
		 List<Customer> findByFixedAreaIdIsNull = customerRepository.findByFixedAreaIdIsNull();
		return findByFixedAreaIdIsNull;
	}
	
	/**
	 * @see cn.itcast.crm.service.ICustomerService#findHasAssociationFixedAreaCustomers(String)
	 */
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(
			String fixedAreaId) {
		List<Customer> findByFixedAreaId = customerRepository.findByFixedAreaId(fixedAreaId);
		return findByFixedAreaId;
	}
	/**
	 * @see cn.itcast.crm.service.ICustomerService#associationCustomersToFixedArea(String, String)
	 */
	@Override
	public void associationCustomersToFixedArea(String customerIdStr,
			String fixedAreaId) {
		
		// 清除原来绑定特定定区的客户
		customerRepository.cleanCustomer(fixedAreaId);
		if("null".equals(customerIdStr)){
			customerIdStr="";
		}
		// 切割获得id集合
		if(StringUtils.isNotBlank(customerIdStr)){
			String[] customerIdArray = customerIdStr.split(",");
			
			for (String idStr : customerIdArray) {
				Integer id = Integer.parseInt(idStr);
				customerRepository.updateFixedAreaId(fixedAreaId,id);
			}
		}
	}
	/**
	 * @see cn.itcast.crm.service.ICustomerService#saveCustomer(Customer)
	 */
	@Override
	public void saveCustomer(Customer customer) {
		customerRepository.save(customer);
		
	}
	
	/**
	 * @see cn.itcast.crm.service.ICustomerService#findByTelephone(String)
	 */
	@Override
	public Customer findByTelephone(String telephone) {
		Customer customer = customerRepository.findByTelephone(telephone);
		return customer;
	}
	
	/**
	 * @see cn.itcast.crm.service.ICustomerService#updateType(String)
	 */
	@Override
	public void updateType(String telephone) {
		
		customerRepository.updateType(telephone);
	}

}
